/*pmFWCFu5nhKkBzYmrkBakfAv9ikyb/StD9QZBFDIlqRZnhBAQmVr9HkjEqBZlOPe*/
//2018.05.03
import constant from '../../constants';
import { toggleShow, queryInventoryWay, loadingResultData } from '../events';
import { detailAreaTableButtonClick, assignAreaTableButtonClick } from './../components/event';
import ampub from 'ampub';
import fa from 'fa';
const { fa_components } = fa;
const { ReferFilter } = fa_components;
const { addSearchAreaReferFilter } = ReferFilter;
const { components, utils, commonConst } = ampub;
const { faQueryAboutUtils, LoginContext, AMTooltip } = components;
const { getContext, loginContextKeys, loginContext } = LoginContext;
const { openAssetCardByPk } = faQueryAboutUtils;
const { cardUtils, multiLangUtils } = utils;
const { getMultiLangByID } = multiLangUtils;
const { afterModifyCardMeta, setHeadAreaData } = cardUtils;
const { CommonKeys, StatusUtils } = commonConst;
const { IBusiRoleConst } = CommonKeys;
const { UISTATE } = StatusUtils;

export default function(props) {
	props.createUIDom(
		{
			pagecode: constant.PAGE_CODE.CARD //页面id
		},
		(data) => {
			if (data) {
				if (data.context) {
					// 初始化上下文变量
					loginContext(data.context);
				}
				if (data.button) {
					let button = data.button;
					modifierButtons.call(this, button);
					props.button.setButtons(button);
				}
				if (data.template) {
					let meta = data.template;
					meta = modifierMeta.call(this, props, meta);
					props.meta.setMeta(meta, () => {
						afterInit.call(this, props);
					});
				}
			}
		}
	);
}

/**
 * 调整按钮最初显隐性
 * 		设置为隐藏
 * 原因：为了避免刚刚刷新界面的时候所有按钮都显示造成的视觉上的冲击
 * @param {*} meta 
 */
function modifierButtons(buttons) {
	buttons.map((button) => {
        //如果button.area中包含inner或者包含assign
		if (!(RegExp(/inner/).test(button.area) || RegExp(/assign/).test(button.area))) {
			if (button.children.length != 0) {
				button.children.map((itemButton) => {
					itemButton.visible = false;
				});
			} else {
				button.visible = false;
			}
		}
	});
}

/**
 * 模板初始化以后
 * @param {*} props 
 */
function afterInit(props) {
	let status = props.getUrlParam('status') || UISTATE.browse;
	let current = this.props.getUrlParam('current');
	//如果current为空，并且状态为browse，可能是通过来源单据跳转过来的，所以默认跳到盘点结果页面
	let pk = this.props.getUrlParam('id');
	if (!current && status == UISTATE.browse) {
		current = '7';
	}
	// 重新分配盘点人
	if (current == '1') {
		this.isFromList = 'true';
		queryInventoryWay.call(this, pk);
	}
	// 查看盘点结果
	if (current == '7') {
		if (pk && pk != 'undefined') {
			loadingResultData.call(this, pk);
		}
	}

	if (status == UISTATE.add) {
		let showdata = { status: 'add', bill_code: null };
		setHeadAreaData.call(this, this.props, showdata);
		//setTitleData.call(this, { bill_code: null, status: 'add' });
	}
	let { form } = props;
	// 为了从列表跳转到卡片，并加载卡片数据
	if (current) {
		let pk_inventory = props.getUrlParam('id');
		let bill_code = props.getUrlParam('bill_code');
		let ts = props.getUrlParam('ts');
		let inventoryStatus = 'confirmed';
		// 把盘点的柱状图数据清空
		this.echartsData.linedata.data = [];
		this.echartsData.linedata.name = [];
		current = current * 1;
		// 重新分配盘点人
		if (current === 1) {
			let total_num = props.getUrlParam('total_num');
			this.echartsData.total_num = total_num;
			this.isFromList = 'true';
			this.setState({ current, pk_inventory, inventoryStatus }, () => {
				toggleShow(this, props);
				//进入分配盘点人区域为编辑态
				this.props.editTable.setStatus(constant.AREA.STEP.ALLOT_CHECKUSER, 'edit');
			});

			// 查看盘点结果
		} else if (current === 7) {
			//this.ts = ts;
			this.bill_code = bill_code;
			let showdata = { status: 'edit', bill_code: null };
			setHeadAreaData.call(this, this.props, showdata);
			//setTitleData.call(this, { bill_code: null, status: 'edit' });
			this.setState({ pk_inventory, inventoryStatus });
			toggleShow(this, props);
		}
	} else {
		props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_ONE_BTNS, true);
		form.setFormStatus('childform2', 'edit');
		// 先清空查询区
		this.props.search.clearSearchArea(constant.AREA.STEP.INVENTORY_RANGE);
		// 默认主组织
		let pk_org = getContext(loginContextKeys.pk_org);
		let org_Name = getContext(loginContextKeys.org_Name);
		let bill_date = getContext(loginContextKeys.businessDate);
		this.props.search.setSearchValByField(constant.AREA.STEP.INVENTORY_RANGE, 'pk_org', {
			value: pk_org,
			display: org_Name
		});
		this.props.form.setFormItemsValue(constant.AREA.STEP.INVENTORY_DATE, {
			start_date: { value: bill_date }
		});
	}
}


//修改meta
function modifierMeta(props, meta) {
	//参照处理
	let pk_org = props.getUrlParam('pk_org');
	this.result_pk_org = pk_org;
	referFilter.call(this, meta);
	addExternal.call(this, props, meta);
	return meta;
}

function addExternal(props, meta) {
	// 添加分配盘点人超链接
	meta[constant.AREA.STEP.ANEWALLOT].items.map((item) => {
		if (item.attrcode == 'pk_card') {
			//给资产编码列添加超链接
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				return (
					<div class="card-table-browse">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									openAssetCardByPk.call(this, props, record.values.pk_card.value);
								}}
							>
								{record && record.values.asset_code && record.values.asset_code.value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
	});
	// 添加穿透列表超链接
	meta[constant.AREA.STEP.DETAIL_LIST].items.map((item) => {
		if (item.attrcode == 'asset_code') {
			//给资产编码列添加超链接
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				if (record.values.check_result.value != '1') {
					return (
						<div class="card-table-browse">
							<AMTooltip nodeType="cardTable">
								<span
									className="code-detail-link"
									onClick={() => {
										openAssetCardByPk.call(this, props, record.values.pk_card.value);
									}}
								>
									{record && record.values.asset_code && record.values.asset_code.value}
								</span>
							</AMTooltip>
						</div>
					);
				}
				return (
					<div class="card-table-browse">
						<span>{record && record.values.asset_code && record.values.asset_code.value}</span>
					</div>
				);
			};
		}
	});
	// 添加分配盘点人操作列
	meta[constant.AREA.STEP.ALLOT_CHECKUSER].items.push({
		label: getMultiLangByID('amcommon-000000') /*操作*/,
		itemtype: 'customer',
		attrcode: 'opr',
		width: '150px',
		visible: true,
		render: (text, record, index) => {
			let buttonAry = constant.STEP_BTNS.STEP_TWO_INNER_BTNS;

			return props.button.createOprationButton(buttonAry, {
				area: 'card_body_inner',
				buttonLimit: 3,
				onButtonClick: (props, key) => {
					assignAreaTableButtonClick.call(this, props, key, text, record, index);
				}
			});
		}
	});
	// 添加穿透列表操作列
	meta[constant.AREA.STEP.DETAIL_LIST].items.push({
		attrcode: 'opr',
		label: getMultiLangByID('amcommon-000000') /*操作*/,
		width: '300px',
		fixed: 'right',
		itemtype: 'customer',
		className: 'table-opr',
		visible: true,
		render: (text, record, index) => {
			let buttonAry = [ 'Detail' ];
			let cardTableStatus = props.cardTable.getStatus(constant.AREA.STEP.DETAIL_LIST);
			if (cardTableStatus == 'edit') {
				buttonAry =
					record.values.check_result.value === null
						? constant.STEP_BTNS.SKIP_INNER_BROWSE_OPEN
						: record.values.check_result.value == 0
							? constant.STEP_BTNS.SKIP_INNER_BROWSE_OPEN
							: record.values.check_result.value == 1
								? constant.STEP_BTNS.SKIP_INNER_BROWSE_PROFIT
								: record.values.check_result.value == 2
									? constant.STEP_BTNS.SKIP_INNER_BROWSE_OFFLOSS
									: record.values.check_result.value == 3
										? constant.STEP_BTNS.SKIP_INNER_BROWSE_OPEN
										: constant.STEP_BTNS.SKIP_INNER_BROWSE_OPEN;
			}
			let buttonarea = props.button.createOprationButton(buttonAry, {
				area: 'card_body_inner',
				buttonLimit: 3,
				onButtonClick: (props, key) => {
					detailAreaTableButtonClick.call(this, props, key, text, record, index);
				}
			});
			return buttonarea;
		}
	});
}

function referFilter(meta) {
	let searchAreaFilterConfig = {
		searchId: 'childform1', //查询区id
		orgField: 'pk_org', //自定义项多组织 组织字段编码
		defPrefix: { search: [ 'bodyvos.def', 'def' ] }
	};
	addSearchAreaReferFilter(this.props, meta, searchAreaFilterConfig);
    meta[constant.AREA.STEP.INVENTORY_RANGE].items.map((item) => {
        if (item.attrcode == 'pk_category' || item.attrcode == 'pk_mandept' || item.attrcode == 'pk_usedept') {
            item.isShowUnit = false;
            item.isMultiSelectedEnabled = true;
            item.onlyLeafCanSelect = false;
            item.isRunWithChildren = true;
            item.defaultRunWithChildren = true;
            
			item.queryCondition = () => {
                if (this.result_pk_org != null) {
                    return { pk_org: this.result_pk_org };
                }
                let pk_org = '';
                if (this.props.search.getSearchValByField(constant.AREA.STEP.INVENTORY_RANGE, 'pk_org').value) {
                    pk_org = this.props.search.getSearchValByField(constant.AREA.STEP.INVENTORY_RANGE, 'pk_org').value
                        .firstvalue;
                }

                return { pk_org: pk_org };
            };
        }
    });
	// 分配盘点人参照处理
	meta[constant.AREA.STEP.ALLOT_CHECKUSER].items.map((item, index, met, value) => {
		if (item.attrcode == 'inventory_checkuser') {
			item.isShowUnit = true;
			item.onlyLeafCanSelect = false;
			item.queryCondition = () => {
				let pk_org = '';
				if (this.result_pk_org != null) {
					return { pk_org: this.result_pk_org, busifuncode: IBusiRoleConst.ASSETORG, isShowUnit: true };
				}
				if (this.props.search.getSearchValByField(constant.AREA.STEP.INVENTORY_RANGE, 'pk_org').value) {
					pk_org = this.props.search.getSearchValByField(constant.AREA.STEP.INVENTORY_RANGE, 'pk_org').value
						.firstvalue;
				}
				return { pk_org: pk_org, busifuncode: IBusiRoleConst.ASSETORG, isShowUnit: true };
			};
		} else if (item.attrcode == 'pk_ownerorg') {
			item.queryCondition = () => {
				let pk_org = '';
				if (this.result_pk_org != null) {
					return { pk_org: this.result_pk_org };
				}
				if (this.props.search.getSearchValByField(constant.AREA.STEP.INVENTORY_RANGE, 'pk_org').value) {
					pk_org = this.props.search.getSearchValByField(constant.AREA.STEP.INVENTORY_RANGE, 'pk_org').value
						.firstvalue;
				}
				return { pk_org: pk_org };
			};
		} else if (item.attrcode == 'pk_dept') {
			// 部门支持多选
			item.isMultiSelectedEnabled = true;
			item.isRunWithChildren = true;
			item.defaultRunWithChildren = true;
			//由于部门和使用权字段参照不是通过元数据拉的，所以参数标题多语需要自己处理
			item.refName = getMultiLangByID('facommon-000016');
			item.refName_db = getMultiLangByID('facommon-000016');
		} else if (item.attrcode == 'pk_equiporg') {
			//使用权
			item.refName = getMultiLangByID('facommon-000001');
			item.refName_db = getMultiLangByID('facommon-000001');
		}
		if (item.attrcode == 'pk_category') {
			// 类别支持多选
			item.isMultiSelectedEnabled = true;
			item.onlyLeafCanSelect = false;
			item.isRunWithChildren = true;
			item.defaultRunWithChildren = true;
			item.queryCondition = () => {
				if (this.result_pk_org != null) {
					return { pk_org: this.result_pk_org };
				}
				let pk_org = '';
				if (this.props.search.getSearchValByField(constant.AREA.STEP.INVENTORY_RANGE, 'pk_org').value) {
					pk_org = this.props.search.getSearchValByField(constant.AREA.STEP.INVENTORY_RANGE, 'pk_org').value
						.firstvalue;
				}
				return { pk_org: pk_org };
			};
		}
	});
	// 未分配盘点人参照处理
	meta[constant.AREA.STEP.ANEWALLOT].items.map((item) => {
		if (item.attrcode == 'inventory_checkuser') {
			item.isShowUnit = true;
			item.queryCondition = () => {
				let pk_org = '';
				if (this.result_pk_org != null) {
					pk_org = this.result_pk_org;
				} else {
					pk_org = this.props.search.getSearchValByField(constant.AREA.STEP.INVENTORY_RANGE, 'pk_org').value
						.firstvalue;
				}
				return { pk_org: pk_org, busifuncode: IBusiRoleConst.ASSETORG, isShowUnit: true };
			};
		}
		if (item.attrcode.includes('def') && item.itemtype == 'refer') {
			item.isShowUnit = true;
			item.queryCondition = () => {
				let pk_org = '';
				if (this.result_pk_org != null) {
					pk_org = this.result_pk_org;
				} else {
					pk_org = this.props.search.getSearchValByField(constant.AREA.STEP.INVENTORY_RANGE, 'pk_org').value
						.firstvalue;
				}
				return { pk_org: pk_org, busifuncode: IBusiRoleConst.ASSETORG, isShowUnit: true };
			};
		}
	});
	// 穿透列表参照处理
	meta[constant.AREA.STEP.DETAIL_LIST].items.map((item) => {
		// 使用人(盘点后)
		if (item.attrcode == 'assetuser_after') {
			item.queryCondition = () => {
				let pk_org = null;
				let index = this.props.cardTable.getCurrentIndex(constant.AREA.STEP.DETAIL_LIST);
				let rowData = this.props.cardTable.getDataByIndex(constant.AREA.STEP.DETAIL_LIST, index);
				// 先参照使用权
				if (
					rowData &&
					rowData.values &&
					rowData.values['pk_equiporg_after'].value &&
					rowData.values['pk_equiporg_after'].value != ''
				) {
					pk_org = rowData.values['pk_equiporg_after'].value;
				} else {
					pk_org = this.echartsData.pk_org;
				}
				return { pk_org: pk_org, busifuncode: IBusiRoleConst.ASSETORG, isShowUnit: true };
			};
		}
		//管理部门编码(盘点后);
		if (item.attrcode == 'pk_mandept_after_v' || item.attrcode == 'pk_mandept_after') {
			item.queryCondition = () => {
				let pk_org = null;
				let index = this.props.cardTable.getCurrentIndex(constant.AREA.STEP.DETAIL_LIST);
				let rowData = this.props.cardTable.getDataByIndex(constant.AREA.STEP.DETAIL_LIST, index);
				// 先参照货主管理组织
				if (
					rowData &&
					rowData.values &&
					rowData.values['pk_ownerorg_after'].value &&
					rowData.values['pk_ownerorg_after'].value != ''
				) {
					pk_org = rowData.values['pk_ownerorg_after'].value;
				} else {
					pk_org = this.echartsData.pk_org;
				}
				return { pk_org: pk_org, busifuncode: IBusiRoleConst.ASSETORG, isShowUnit: true };
			};
		}
		// 货主管理组织编码(盘点后)
		if (item.attrcode == 'pk_ownerorg_after_v') {
			item.queryCondition = () => {
				let pk_org = this.echartsData.pk_org;
				return {
					pk_org: pk_org,
					TreeRefActionExt: 'nccloud.web.fa.newasset.transasset.refcondition.PK_OWNERORG_VSqlBuilder'
				};
			};
		}
		// 使用部门(盘点后)
		if (item.attrcode == 'pk_usedept_after_v' || item.attrcode == 'pk_usedept_after') {
			item.queryCondition = () => {
				let pk_org = null;
				let index = this.props.cardTable.getCurrentIndex(constant.AREA.STEP.DETAIL_LIST);
				let rowData = this.props.cardTable.getDataByIndex(constant.AREA.STEP.DETAIL_LIST, index);
				// 先参照使用权
				if (
					rowData &&
					rowData.values &&
					rowData.values['pk_equiporg_after'].value &&
					rowData.values['pk_equiporg_after'].value != ''
				) {
					pk_org = rowData.values['pk_equiporg_after'].value;
				} else {
					pk_org = this.echartsData.pk_org;
				}
				return { pk_org: pk_org, busifuncode: IBusiRoleConst.ASSETORG, isShowUnit: true };
			};
		}
		if (item.attrcode == 'pk_mandept_before_v' || item.attrcode == 'pk_mandept_before') {
			item.queryCondition = () => {
				let pk_org = this.echartsData.pk_org;
				return { pk_org: pk_org, busifuncode: IBusiRoleConst.ASSETORG, isShowUnit: true };
			};
		}
		if (item.attrcode == 'inventory_checkuser') {
			item.queryCondition = () => {
				let pk_org = this.echartsData.pk_org;
				return { pk_org: pk_org, busifuncode: IBusiRoleConst.ASSETORG, isShowUnit: true };
			};
		}
		if (item.attrcode == 'pk_category') {
			item.queryCondition = () => {
				let pk_org = this.echartsData.pk_org;
				return { pk_org: pk_org };
			};
		}
		if (item.attrcode.includes('def') && item.itemtype == 'refer') {
			item.queryCondition = () => {
				let pk_org = this.echartsData.pk_org;
				return { pk_org: pk_org };
			};
		}
	});
	// 拷贝列表参照过滤等配置到展开
	meta = afterModifyCardMeta.call(this, this.props, meta);
}

/*pmFWCFu5nhKkBzYmrkBakfAv9ikyb/StD9QZBFDIlqRZnhBAQmVr9HkjEqBZlOPe*/